package com.weibopay.gf.service;

import cn.hutool.http.*;
import com.alibaba.fastjson.JSONObject;
import com.weibopay.gf.support.ApiUrl;
import com.weibopay.gf.util.CommonUtils;
import com.weibopay.gf.util.SignUtils;

/**
 * A类业务
 */
public class ApiService {

    private final String API_URL;

    public ApiService(String API_URL) {
        this.API_URL = API_URL;
    }

    /**
     * API请求
     */
    public String apiRequest(String requestBody) {
        JSONObject param = JSONObject.parseObject(requestBody);
        //过滤无需加签的参数
        CommonUtils.filter(param);
        //针对请求参数进行签名
        String sign = SignUtils.init(ApiUrl.publicKey, ApiUrl.privateKey).sign(param);
        //追加请求参数
        param.put("sign", sign);
        param.put("sign_type", "RSA");
        //发送HTTP请求
        HttpRequest post = HttpUtil.createPost(API_URL);
        post.contentType(ContentType.JSON.getValue());
        post.body(param.toJSONString());
        HttpResponse httpResponse = post.execute();

        if (httpResponse.getStatus() == HttpStatus.HTTP_OK) {
            return httpResponse.body();
        }
        System.err.println("请求异常:" + httpResponse.getStatus() + "-" + httpResponse.body());
        return httpResponse.body();
    }
}
